<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="会议主题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入会议主题" />
      </el-form-item>
      <el-form-item label="会议时间" prop="meetingTime">
        <el-date-picker
          v-model="formData.meetingTime"
          type="date"
          value-format="x"
          placeholder="选择会议时间"
        />
      </el-form-item>
      <el-form-item label="会议室" prop="roomId">
        <el-select
          v-model="formData.roomId"
          filterable
          placeholder="请选择会议室"
          style="width: 100%"
        >
          <el-option
            v-for="room in meetingRooms"
            :key="room.id"
            :label="room.meetingName"
            :value="room.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="主持人" prop="hostUserId">
        <UserSelect @node-change="(row) => handleNodeChange(row, 'hostUserId')" v-model="formData.hostUserId" placeholder="请选择主持人"/>
      </el-form-item>

      <el-form-item label="记录人" prop="recorderUserId">
        <UserSelect @node-change="(row) => handleNodeChange(row, 'recorderUserId')" v-model="formData.recorderUserId" placeholder="请选择记录人"/>
      </el-form-item>

      <el-form-item label="主办部门" prop="departmentId">
        <el-select v-model="formData.departmentId" placeholder="请选择主办部门" filterable clearable class="w-100%">
          <el-option
            v-for="dept in deptList"
            :key="dept.id"
            :label="dept.name"
            :value="dept.name"
          />
        </el-select>
      </el-form-item>

      <!-- 参会人员 - 使用 UserSelectDialog 多选模式 -->
      <el-form-item label="参会人员" prop="meetingParticipants">
        <div>
          <!-- 显示已选择的参会人员 -->
          <div v-if="selectedParticipants.length > 0" class="mb-2">
            <el-tag
              v-for="user in selectedParticipants"
              :key="user.id"
              closable
              @close="removeParticipant(user.id)"
              type="primary"
              class="mr-2 mb-2"
            >
              {{ user.nickname }}({{ user.username }})
            </el-tag>
          </div>

          <!-- 选择按钮 -->
          <el-button @click="openParticipantDialog" type="primary" plain>
            <Icon icon="ep:plus" />
            选择参会人员{{ selectedParticipants.length > 0 ? `(${selectedParticipants.length})` : '' }}
          </el-button>
        </div>
      </el-form-item>

      <el-form-item label="会议内容" prop="content">
        <el-input v-model="formData.content" type="textarea" :rows = "4" placeholder="请输入内容" />
      </el-form-item>
      <el-form-item label="下一步计划" prop="nextPlan">
        <el-input v-model="formData.nextPlan" type="textarea" :rows = "4"  placeholder="请输入下一步计划" />
      </el-form-item>
      <el-form-item label="备注信息" prop="remark">
        <el-input v-model="formData.remark"  type="textarea"  :rows = "4"  placeholder="请输入备注信息" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 参会人员选择对话框 -->
  <UserSelectDialog
    v-model="participantDialogVisible"
    :multiple="true"
    :selected-ids="selectedParticipantIds"
    title="选择参会人员"
    @confirm="handleParticipantConfirm"
  />
</template>

<script setup lang="ts">
import { MeetingRecordApi, MeetingRecordVO } from '@/api/oa/meetingrecord'
import { MeetingRoomApi } from '@/api/oa/meetingroom'
import { onMounted } from 'vue'
import UserSelect from '@/views/system/user/UserSelect.vue'
import UserSelectDialog from '@/views/system/user/UserSelectDialog.vue'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'

/** 会议记录主 表单 */
defineOptions({ name: 'MeetingRecordForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const deptList = ref([])

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

// 参会人员相关
const participantDialogVisible = ref(false)
const selectedParticipants = ref<UserApi.UserVO[]>([])
const selectedParticipantIds = computed(() => selectedParticipants.value.map(user => String(user.id)))

const formData = ref({
  id: undefined,
  title: undefined,
  meetingTime: undefined,
  roomId: undefined,
  hostUserId: undefined,
  recorderUserId: undefined,
  departmentId: undefined,
  meetingParticipants: undefined,
  content: undefined,
  nextPlan: undefined,
  remark: undefined
})

const formRules = reactive({
  title: [{ required: true, message: '会议主题不能为空', trigger: 'blur' }],
  meetingTime: [{ required: true, message: '会议时间不能为空', trigger: 'blur' }],
  roomId: [{ required: true, message: '会议室不能为空', trigger: 'blur' }],
  hostUserId: [{ required: true, message: '主持人不能为空', trigger: 'blur' }],
  recorderUserId: [{ required: true, message: '记录人不能为空', trigger: 'blur' }],
  departmentId: [{ required: true, message: '主办部门不能为空', trigger: 'blur' }],
  meetingParticipants: [{ required: true, message: '参会人员不能为空', trigger: 'blur' }],
  content: [{ required: true, message: '会议内容不能为空', trigger: 'blur' }]
})

const formRef = ref() // 表单 Ref
const meetingRooms = ref([]) // 存储会议室列表

// 获取会议室列表
const getMeetingRoomList = async () => {
  try {
    const data = await MeetingRoomApi.getMeetingRoomPage({status: 1})
    meetingRooms.value = data.list
  } catch (error) {
    console.error('获取会议室失败:', error)
  }
}

onMounted(() => {
  getMeetingRoomList()
  loadDeptList()
})

const loadDeptList = async () => {
  try {
    deptList.value = await DeptApi.getDeptPage({})
    console.log('【DeptApi】获取部门列表成功:', deptList.value)
  } catch (error) {
    console.error('获取部门列表失败', error)
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  if (id) {
    formLoading.value = true
    try {
      const record = await MeetingRecordApi.getMeetingRecord(id)

      // 加载会议室列表（如果还未加载）
      if (meetingRooms.value.length === 0) {
        await getMeetingRoomList()
      }

      // 设置表单数据
      formData.value = {
        ...record,
        roomId: record.roomId || undefined
      }

      // 如果有参会人员数据，需要解析并设置选中的参会人员
      if (record.meetingParticipants) {
        await loadSelectedParticipants(record.meetingParticipants)
      }
    } finally {
      formLoading.value = false
    }
  }
}

/** 根据参会人员字符串加载用户信息 */
const loadSelectedParticipants = async (participantsStr: string) => {
  try {
    // 假设参会人员字段存储的是用户ID，用逗号分隔
    // 如果存储格式不同，需要根据实际情况调整解析逻辑
    const userIds = participantsStr.split(',').map(id => id.trim()).filter(id => id)

    if (userIds.length > 0) {
      const users = await Promise.all(
        userIds.map(async (id) => {
          try {
            return await UserApi.getUser(Number(id))
          } catch {
            return null
          }
        })
      )
      selectedParticipants.value = users.filter(user => user !== null) as UserApi.UserVO[]
    }
  } catch (error) {
    console.error('加载参会人员失败:', error)
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 打开参会人员选择对话框 */
const openParticipantDialog = () => {
  participantDialogVisible.value = true
}


/** 处理参会人员选择确认 */
const handleParticipantConfirm = (users: UserApi.UserVO[], ids: string[]) => {
  selectedParticipants.value = users
  // 更新表单数据 - 这里可以根据实际需求存储用户ID或其他格式
  formData.value.meetingParticipants = ids.join(',')

  console.log('选择的参会人员:', users)
  console.log('参会人员IDs:', ids)
}

/** 移除参会人员 */
const removeParticipant = (userId: number) => {
  const index = selectedParticipants.value.findIndex(user => user.id === userId)
  if (index > -1) {
    selectedParticipants.value.splice(index, 1)
    // 更新表单数据
    const remainingIds = selectedParticipants.value.map(user => String(user.id))
    formData.value.meetingParticipants = remainingIds.join(',')
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MeetingRecordVO
    if (formType.value === 'create') {
      await MeetingRecordApi.createMeetingRecord(data)
      message.success(t('common.createSuccess'))
    } else {
      await MeetingRecordApi.updateMeetingRecord(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    title: undefined,
    meetingTime: undefined,
    roomId: undefined,
    hostUserId: undefined,
    recorderUserId: undefined,
    departmentId: undefined,
    meetingParticipants: undefined,
    content: undefined,
    nextPlan: undefined,
    remark: undefined
  }
  // 重置参会人员选择
  selectedParticipants.value = []
  formRef.value?.resetFields()
  formData.value.meetingParticipants = ''
}

/** 员工被点击事件 - 支持动态字段 */
const handleNodeChange = (row, field) => {
  console.log('【UserSelect】选中用户对象:', row)
  console.log('用户ID:', row?.id)
  console.log('用户昵称:', row?.nickname)

  // 动态设置对应的字段
  formData.value[field] = row.id
  formData.value.nickName = row.nickname
}
</script>

<style scoped>
.mr-2 {
  margin-right: 8px;
}

.mb-2 {
  margin-bottom: 8px;
}
</style>
